<?php
/**
 * Yd标签库解析类
 *
 * @package         YDCMS
 * @author          QQ:644157559 <644157559@qq.com>
 * @version         $Id: Yd.class.php v1.0 2014-06-13 17:27:03 $
 */
namespace Think\Template\TagLib;
use Think\Template\TagLib;
class Yd extends TagLib{
    // 标签定义
    protected $tags   =  array(
            // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
            'arclist'   =>  array('attr' => 'typeid,flag,noflag,row,infolen,titlelen,orderby,keyword,limit,lang,key,mod,addfields,mid,empty', 'level' => 1),
            'channel'   =>  array('attr' => 'id,type,typeid,row,reid,lang,key,mod,soncat,empty,fields', 'level' => 3),
            'flink'   =>  array('attr' => 'id,row', 'level' => 1),
            'mylang'    =>  array('attr'=>'eid,lang','close'=>0),
            'myad'    =>  array('attr'=>'tag', 'close'=>0),
            'type'    =>  array('attr'=>'typeid,fields,lang','level'=>1),
            );
    
    /**
     * arclist标签解析
     * 格式：
     * <arclist typeid="1" flag="c" noflag="p" row="10" infolen="150" titlelen="40" id="arc" empty="" lang="zh-cn">
     * {arc.title}
     * {arc.arcurl}
     * </arclist>
     * @access public
     * @param array $tag
     * @param string $content
     * @return string
     */
    public function _arclist($tag,$content) {
        $id         = isset($tag['id']) ? $tag['id'] : 'field';
        $typeid     = isset($tag['typeid']) ? $tag['typeid'] : 0;
        $line       = isset($tag['row']) ? $tag['row'] : 10;
        $limit      = isset($tag['limit']) ? $tag['limit'] : '';
        $titlelen   = isset($tag['titlelen']) ? $tag['titlelen'] : 30;
        $infolen    = isset($tag['infolen']) ? $tag['infolen'] : 160;
        $model_id   = isset($tag['mid']) ? $tag['mid'] : 0;
        $orderby    = isset($tag['orderby']) ? $tag['orderby'] : 'c.id desc';
        $att        = isset($tag['flag']) ? $tag['flag'] : '';
        $noflag     = isset($tag['noflag']) ? $tag['noflag'] : '';
        $keyword    = isset($tag['keyword']) ? $tag['keyword'] : '';
        $addfield   = isset($tag['addfields']) ? $tag['addfields'] : '';
        
        
        $lang       = isset($tag['lang']) ? trim($tag['lang']) :(cookie('think_language') ? cookie('think_language') : 'zh-cn');//语言标识
        $lang       = TagCheckLang($lang);
        
        $empty      = isset($tag['empty']) ? $tag['empty'] : '';
        $key        = !empty($tag['key']) ? $tag['key'] : 'i';
        $mod        = isset($tag['mod']) ? $tag['mod'] : '2';
        $orwheres = array();
        $orwheres['c.lang'] = $lang;
        
        $ContypeModel = D("Contype");
        if(empty($typeid)) {
            $typeid = ( isset($ContypeModel->TypeInfos['id']) ? $ContypeModel->TypeInfos['id'] : $typeid );
        }
        //栏目ID
        if(!empty($typeid) && $typeid != 'top') {
            //指定了多个栏目时，不再获取子类的id
            if( preg_match('#,#', $typeid) )
            {
                //指定了getall属性或主页模板例外
                if(empty($ContypeModel->TypeInfos['id'])){
                    $typeids = explode(',', $typeid);
                    foreach($typeids as $ttid) {
                        $sonids = $ContypeModel->getSonId($ttid);
                        $typeidss[] = join(",", $sonids);
                    }
                    $typeidStr = join(',', $typeidss);
                    $typeidss = explode(',', $typeidStr);
                    $typeidssok = array_unique($typeidss);
                    $typeid = join(',', $typeidssok);
                }
                $orwheres["c.typeid"] = array("in", $typeid);
            }else{
                $ContypeModel->idArray = "";
                $sonids = $ContypeModel->getSonId($typeid);
                $sonids = join(",", $sonids);
                $orwheres["c.typeid"] = array("in", $sonids);
            }
        }
        //模型ID
        if(!empty($model_id)){
            $orwheres["c.mid"] = $model_id;
        }
        //limit
        if($limit != '') {
            $limitarr = explode(',', $limit);
            $line = isset($limitarr[1]) ? $limit : $line;
        }
        //需要拼接成字符串的查询条件数组
        $whereStringArr = array();
        
        //关键字条件
        if($keyword != ''){
            $keyword = str_replace(',', '|', $keyword);
            $whereStringArr[] = " CONCAT(c.title,c.keywords) REGEXP '$keyword' ";
        }
        
        //文档属性
        if($att != '') {
            $flags = explode(',', $att);
            for($i=0; isset($flags[$i]); $i++) {
                $whereStringArr[] = " FIND_IN_SET('{$flags[$i]}', c.flag) > 0 ";
            }
        }
        if(!empty($noflag)) {
            if(!preg_match('#,#', $noflag)) {
                $whereStringArr[] = " FIND_IN_SET('$noflag', c.flag) < 1 ";
            } else {
                $noflags = explode(',', $noflag);
                foreach($noflags as $noflag) {
                    if(trim($noflag)==''){
                        continue;
                    }
                    $whereStringArr[] = " FIND_IN_SET('{$noflag}', c.flag) < 1 ";
                }
            }
        }
        //拼接文档属性查询条件
        if(isArrayAndNotEmpty($whereStringArr)){
            $orwheres['_string'] = implode(" AND ", $whereStringArr);
        }
        
        
        $join = array();
        $join[] = " __CONTYPE__ tp ON c.typeid=tp.id";
        $addfieldsSql = '';
        //获取附加表信息
        if($addfield != '' && !empty($model_id))
        {
            $ModelInfo = M("Model")->field("addtable")->getById($model_id);
            if(isset($ModelInfo['addtable']) && trim($ModelInfo['addtable']) != '')
            {
                $addtable = "__" . strtoupper(trim($ModelInfo['addtable'])) . "__";
                $addfields = explode(',', $addfield);
                $join[] = $addtable . " addf ON addf.aid = c.id";
                $addfieldsSql = ",addf.".join(',addf.', $addfields);
            }
        }
        $fields = "c.*,tp.typedir,tp.typename,tp.isdefault,tp.defaultname,tp.namerule,tp.namerule2,tp.ispart{$addfieldsSql}";
        //var_dump($orwheres);
        $result = D("Content")->getArcList($orwheres, $fields, $limit, $orderby, $join);
        //. 'var_dump($ContypeModel);die;'
        $parseStr   =  '<?php ';
        $name   = addslashes(serialize($result));
        
        $parseStr  .=  '$__LIST__ = unserialize(stripslashes(\''.$name.'\'));if(is_array($__LIST__)): $'.$key.' = 0;';        
        $parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;';
        $parseStr .= 'else: ';
        $parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): ';
        $parseStr .= '$'.$id.'["arcurl"] = GetFileUrl($'.$id.'["id"],$'.$id.'["typeid"],$'.$id.'["pubdate"],$'.$id.'["title"],$'.$id.'["ismake"],$'.$id.'["namerule"],$'.$id.'["typedir"],$'.$id.'["filename"]);';
        $parseStr .= '$'.$id.'["typeurl"] = GetTypeUrl($'.$id.'["typeid"],$'.$id.'["typedir"],$'.$id.'["isdefault"],$'.$id.'["defaultname"],$'.$id.'["ispart"],$'.$id.'["namerule2"]);';
        $parseStr .= '$'.$id.'["info"] = $'.$id.'["infos"] = cn_substr($'.$id.'["description"],' . $infolen . ');';
        $parseStr .= '$'.$id.'["fulltitle"] = $'.$id.'["title"];';
        $parseStr .= '$'.$id.'["title"] = cn_substr($'.$id.'["title"],' . $titlelen . ');';
        $parseStr .= '$'.$id.'["stime"] = GetDateTimeMk($'.$id.'["pubdate"]);';
        $parseStr .= '$'.$id.'["litpic"] = isLitpic($'.$id.'["litpic"]);';
        $parseStr .= 'if( $'.$id.'["color"] != "" ) : $'.$id.'["title"] = "<font color=\'".$'.$id.'["color"]."\'>".$'.$id.'["title"]."</font>"; endif;';
        $parseStr .= 'if(preg_match(\'#b#\', $'.$id.'["flag"])) : $'.$id.'["title"] = "<strong>".$'.$id.'["title"]."</strong>"; endif;';
        
        $parseStr .= '$mod = ($'.$key.' % '.$mod.' );';
        $parseStr .= '++$'.$key.';?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>';
        if(!empty($parseStr)) {
            return $parseStr;
        }
        return ;
    }
    
    /**
     * channel标签解析 根据条件获取栏目
     * 
     * @access public
     * @param array $tag 标签属性
     * @param string $content  标签内容
     * @return string|void
     */
    public function _channel($tag, $content) {
        //type,typeid,row,reid
        $id     =    isset($tag['id']) ? trim($tag['id']) : 'field';
        $fields =    '*';//isset($tag['fields']) ? trim($tag['fields']) : '*';
        $type   =    isset($tag['type']) ? trim($tag['type']) : 'son';  //son表示下级栏目,self表示同级栏目,top顶级栏目
        $typeid =    isset($tag['typeid']) ? intval($tag['typeid']) : "0";//栏目ID
        $reid   =    isset($tag['reid']) ? intval($tag['reid']) : "0";//上级栏目ID
        $line   =    isset($tag['row']) ? intval($tag['row']) : "100";//调用栏目数
        $lang   =    isset($tag['lang']) ? trim($tag['lang']) :(cookie('think_language') ? cookie('think_language') : 'zh-cn');//语言标识
        $lang   =    TagCheckLang($lang);
        $empty  =    isset($tag['empty']) ? $tag['empty'] : '';
        $key    =    !empty($tag['key']) ? $tag['key'] : 'i';
        $mod    =    isset($tag['mod']) ? $tag['mod'] : '2';
        $soncat =    isset($tag['soncat']) == 'yes' ? true : false;
        $ContypeModel = D("Contype");
        if($typeid == 0){
            if( isset($ContypeModel->TypeInfos['id']) ){
                $typeid = $ContypeModel->TypeInfos["id"];
                $reid = $ContypeModel->TypeInfos["reid"];
                $topid = $ContypeModel->TypeInfos["topid"];
                $lang = $ContypeModel->TypeInfos["lang"];
            }else{
                $typeid = 0;
            }
        }else{
            $typeinfo = $ContypeModel->getById($typeid);
            $typeid = $typeinfo["id"];
            $reid = $typeinfo["reid"];
            $topid = $typeinfo["topid"];
            $lang = $typeinfo["lang"];
        }
        switch ($type) {
            case "top":
                $where = array();
                $where['reid'] = 0;
                $where['lang'] = $lang;
                $where['ishidden'] = array("NEQ", 1);
                $field = $fields;
                $limit = "0, {$line}";
                $orderby = 'sortrank asc';
                break;
            case "self":
                $where = array();
                $where['reid'] = $reid;
                $where['lang'] = $lang;
                $where['ishidden'] = array("NEQ", 1);
                $field = $fields;
                $limit = "0, {$line}";
                $orderby = 'sortrank asc';
                break;
            default:
                $where = array();
                $where['reid'] = $typeid;
                $where['lang'] = $lang;
                $where['ishidden'] = array("NEQ", 1);
                $field = $fields;
                $limit = "0, {$line}";
                $orderby = 'sortrank asc';
                break;
        }
        $result = D("Contype")->getType($where, $field, $limit, $orderby, $soncat);
        $totalRow = count($result);
        if($totalRow == 0 && $type == 'son'){// && $reid > 0
            $where = array();
            $where['reid'] = $reid;
            $where['lang'] = $lang;
            $where['ishidden'] = array("NEQ", 1);
            $field = $fields;
            $limit = "0, {$line}";
            $orderby = 'sortrank asc';
            $result = D("Contype")->getType($where, $field, $limit, $orderby);
        }
        //var_dump($result);die;
        $parseStr   =  '<?php ';
        $name   = addslashes(serialize($result));
        //echo($name);die;
        $parseStr  .=  '$__LIST__ = unserialize(stripslashes(\''.$name.'\'));if(is_array($__LIST__)): $'.$key.' = 0;';
        $parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;';
        $parseStr .= 'else: ';
        $parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): ';
        $parseStr .= '$mod = ($'.$key.' % '.$mod.' );';
        $parseStr .= '++$'.$key.';?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>';

        if(!empty($parseStr)) {
            return $parseStr;
        }
        return ;
    }
    
    /**
     * 获取栏目信息
     * @access public
     * @param array $tag
     * @param string $content
     */
    public function _type($tag, $content) {
        $id     =    isset($tag['id']) ? trim($tag['id']) : 'field';
        $fields =    '*';//isset($tag['fields']) ? trim($tag['fields']) : '*';
        $typeid =    isset($tag['typeid']) ? $tag['typeid'] : 0;
        $lang   =    isset($tag['lang']) ? trim($tag['lang']) :(cookie('think_language') ? cookie('think_language') : 'zh-cn');//语言标识
        $lang   =    TagCheckLang($lang);
        $empty  =    isset($tag['empty']) ? $tag['empty'] : '';
        $key    =    !empty($tag['key']) ? $tag['key'] : 'i';
        $mod    =    isset($tag['mod']) ? $tag['mod'] : '2';
        if(strpos($typeid, ",")){
            $where = array("id" => array("in", $typeid), "lang" => $lang);
        }else{
            $where = array("id" => intval($typeid));
        }
        $field = $fields;
        $limit = "1";
        
        $result = D("Contype")->getType($where, $field, $limit);
        //var_dump($result);die;
        $parseStr   =  '<?php ';
        
        $name   = addslashes(serialize($result));
        $parseStr  .=  '$__LIST__ = unserialize(stripslashes(\''.$name.'\'));if(is_array($__LIST__)): $'.$key.' = 0;';
        $parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;';
        $parseStr .= 'else: ';
        $parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): ';
        //$row['typelink'] = $row['typeurl'] = GetOneTypeUrlA($row);
        $parseStr .= '$'.$id.'["typelink"] = $'.$id.'["typeurl"] = GetOneTypeUrlA($'.$id.');';
        $parseStr .= '$mod = ($'.$key.' % '.$mod.' );';
        $parseStr .= '++$'.$key.';?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>';

        if(!empty($parseStr)) {
            return $parseStr;
        }
        return ;
    }
    
    /**
     * flink标签解析 根据条件获取栏目
     * 
     * @access public
     * @param array $tag 标签属性
     * @param string $content  标签内容
     * @return string|void
     */
    public function _flink($tag, $content) {
        $id     =    isset($tag['id']) ? trim($tag['id']) : 'field';
        $line   =    isset($tag['row']) ? intval($tag['row']) : "100";//调用行数
        $empty  =    isset($tag['empty']) ? $tag['empty'] : '';
        $key    =    !empty($tag['key']) ? $tag['key'] : 'i';
        $mod    =    isset($tag['mod']) ? $tag['mod'] : '2';
        
        $where = array("status" => 1);
        $field = "*";
        $result = D("Flink")->field($field)->where($where)->order("sortrank ASC")->limit($line)->select();
        //var_dump($result);die;
        $parseStr   =  '<?php ';
        
        $name   = addslashes(serialize($result));
        $parseStr  .=  '$__LIST__ = unserialize(stripslashes(\''.$name.'\'));if(is_array($__LIST__)): $'.$key.' = 0;';
        $parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;';
        $parseStr .= 'else: ';
        $parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): ';
        $parseStr .= '$mod = ($'.$key.' % '.$mod.' );';
        $parseStr .= '++$'.$key.';?>';
        $parseStr .= $this->tpl->parse($content);
        $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>';

        if(!empty($parseStr)) {
            return $parseStr;
        }
        return ;
    }
    /**
     * 自定义资料调用
     * @param array $tag
     * @return string
     */
    public function _mylang($tag) {
        $eid    = $tag['eid'];
        $lang   = isset($tag['lang']) ? trim($tag['lang']) :(cookie('think_language') ? cookie('think_language') : 'zh-cn');//语言标识
        $lang   = TagCheckLang($lang);
        $MylangModel = D("Mylang");
        $where = array('eid' => $eid, "lang" => $lang);
        $langtxt = $MylangModel->field("langtxt")->where($where)->find();
        $parseStr = '<?php echo htmlspecialchars_decode("'.$langtxt['langtxt'].'"); ?>';
        return $parseStr;
    }
    /**
     * 广告调用
     * @param array $tag
     * @return string
     */
    public function _myad($tag) {
        $tagname    = $tag['tag'];
        $MylangModel = D("Myad");
        $where = array('tagname' => $tagname);
        $myad = $MylangModel->where($where)->find();
        $showTxt = '';
        if($myad['timeset'] == 1 && $myad['endtime'] < time()){
            $showTxt = $myad['expbody'];
        }else if($myad['timeset'] == 1 && $myad['starttime'] > time()){
            $showTxt='';
        }else{
            $showTxt = $myad['normbody'];
        }
        $parseStr = '<?php echo ("'.$showTxt.'"); ?>';
        return $parseStr;
    }
}
